package com.yc.easy.res;

import com.yc.easy.bean.EasyProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @program: C0-S3-Ply-hwc-single
 * @description:
 * @author: 作者
 * @create: 2022-11-17 11:01
 */
@Component
public class PropRes {

    private EasyProperties easyProps;
    private long version;
    private File propFile;
    private Properties props;

    public PropRes(EasyProperties easyProps) {
        this.easyProps = easyProps;
        propFile = new File(easyProps.getPropPath());
        if (!propFile.isFile()) {
            throw new RuntimeException("配置文件读取失败: " + propFile);
        }
        props = new Properties();
    }

    public Properties getProps() {
        if (propFile.lastModified() != version) {
            version = propFile.lastModified();
            try (FileInputStream fis = new FileInputStream(propFile);
                 InputStreamReader isr = new InputStreamReader(fis, "utf-8")) {
                props.load(isr);
            } catch (IOException e) {
                throw new RuntimeException("配置文件读取失败: " + propFile, e);
            }
        }
        return props;
    }

    public String getProp(String name) {
        return getProps().getProperty(name);
    }

}
